﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;

using System.Linq;
using System.Text;
using WinnerCMS.Common;
using WinnerCMS.Model;
using WinnerCMS.Model.Enum;

namespace WinnerCMS.Data
{
    /// <summary>
    /// DA_Special 的摘要说明。
    /// </summary>
    public class SpecialDal
    {
        public static readonly Dictionary<int, Special> Alllist;
        static SpecialDal()
        {
            Alllist = new SpecialDal().GetInfos();
        }

        #region 添加专题
        /// <summary>
        /// 添加专题
        /// </summary>
        /// <param name="model"></param>
        public int Add(Special model)
        {
            using (Entities db = new Entities())
            {
                model.Path = string.Empty;
                if (model.ParentId == 0)//如果是要添加顶级栏目
                {
                    bool exists = db.Specials.Any();
                    if (exists == false)
                    {
                        db.Specials.Add(model);
                        db.SaveChangesAsync().Wait();
                    }
                    else
                    {
                        model.OrderId = db.Specials.Select(x => x.OrderId).DefaultIfEmpty(-1).Max() + 1;
                        db.Specials.Add(model);
                        db.SaveChangesAsync().Wait();
                    }
                    model.Path = "|" + model.Id + "|";
                    db.SaveChangesAsync().Wait();
                }
                else//如果不是要添加顶级栏目
                {
                    var pinfo = db.Specials.FirstOrDefault(x => x.Id == model.ParentId);

                    var orther = from x in db.Specials
                                 where x.OrderId > pinfo.OrderId
                                 && !x.Path.StartsWith(pinfo.Path)
                                 select x;
                    foreach (var v in orther)
                    {
                        v.OrderId = v.OrderId + 1;
                    }
                    db.SaveChangesAsync().Wait();


                    model.OrderId = db.Specials.Where(x => x.Path.StartsWith(pinfo.Path)).Select(x => x.OrderId).DefaultIfEmpty(-1).Max() + 1;

                    db.Specials.Add(model);
                    db.SaveChangesAsync().Wait();

                    model.Path = pinfo.Path + model.Id + "|";
                    db.SaveChangesAsync().Wait();
                }

            }
            return model.Id;
        }
        #endregion

        #region 保存专题
        /// <summary>
        /// 保存专题
        /// </summary>
        /// <param name="model"></param>
        public void Edit(Special model)
        {
            using (Entities db = new Entities())
            {
                db.Specials.Attach(model);
                db.Entry(model).State = EntityState.Modified;
                db.SaveChangesAsync().Wait();
            }
        }
        #endregion

        #region 修改内容专题，加载数据
        /// <summary>
        /// 修改内容专题，加载数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Special GetInfo(int id)
        {
            using (Entities db = new Entities())
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Specials.Find(id);
            }
        }
        #endregion

        /// <summary>
        /// 检查一下专题下面是否还有数据
        /// </summary>
        /// <param name="specialId"></param>
        /// <returns></returns>
        public int HaveData(int specialId)
        {
            using (Entities db = new Entities())
            {
                return 1;
            }
        }

        #region 取得所有栏目信息
        /// <summary>
        /// 取得所有栏目信息
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, Special> GetInfos()
        {
            using (Entities db = new Entities())
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Specials.AsNoTracking().ToDictionary(x => x.Id, x => x);
            }
        }

        #endregion

        /// <summary>
        /// 給内容专题管理绑定数据
        /// </summary>
        /// <returns></returns>
        public IList<Special> BindList(byte modelId)
        {
            IList<Special> list = SpecialDataSouce(BindOption.All, modelId);

            return list;
        }

        #region 绑定专题的数据源

        /// <summary>
        /// 绑定专题的数据源
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        private static IList<Special> SpecialDataSouce(BindOption Type, byte? modelId)
        {
            if (Type == BindOption.NoLink)//不显示外部链接的专题
            {
                using (Entities db = new Entities())
                {
                    var q = from x in db.Specials
                            where x.LinkUrl == ""
                            select new { Id = x.Id, SpecialName = x.SpecialName, Path = x.Path };
                    return q.ToArray().Select(x => new Special() { Id = x.Id, SpecialName = x.SpecialName, Path = x.Path }).ToArray();
                }
            }
            if (Type == BindOption.All)
            {
                using (Entities db = new Entities())
                {
                    var q = from x in db.Specials

                            orderby x.OrderId
                            select new { Id = x.Id, SpecialName = x.SpecialName, Path = x.Path, LinkUrl = x.LinkUrl, OrderId = x.OrderId };
                    return q.ToArray().Select(x => new Special() { Id = x.Id, SpecialName = x.SpecialName, Path = x.Path, LinkUrl = x.LinkUrl, OrderId = x.OrderId }).ToArray();
                }
            }
            return null;
        }

        /// <summary>
        /// 改变数据样式
        /// </summary>
        /// <param name="type"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public IList<Special> Bind_DDL(BindOption type, byte? modelId)
        {
            return SpecialDataSouce(type, modelId);
        }

        #endregion



        /// <summary>
        /// 专题排序
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="type"></param>
        public void OrderByMove(int Id, string type)
        {
            using (Entities db = new Entities())
            {
                var info = db.Specials.Find(Id);
                if (type.ToUpper() == "UP")
                {
                    #region MyRegion
                    //上面的栏目
                    var Pre = db.Specials.Where(x => x.ParentId == info.ParentId && x.OrderId < info.OrderId).OrderByDescending(x => x.OrderId).FirstOrDefault();
                    if (Pre != null)
                    {
                        int MyOrderId = info.OrderId, PreOrderId = Pre.OrderId;

                        info.OrderId = PreOrderId;
                        Pre.OrderId = MyOrderId;

                        db.SaveChangesAsync().Wait();
                    }
                    #endregion
                }
                else
                {
                    #region MyRegion
                    //下面的栏目
                    var next = db.Specials.Where(x => x.ParentId == info.ParentId && x.OrderId > info.OrderId).OrderBy(x => x.OrderId).FirstOrDefault();
                    if (next != null)
                    {
                        int MyOrderId = info.OrderId, NextOrderId = next.OrderId;

                        info.OrderId = NextOrderId;
                        next.OrderId = MyOrderId;

                        db.SaveChangesAsync().Wait();
                    }

                    #endregion
                }
            }
        }

        /// <summary>
        /// 删除专题
        /// </summary>
        /// <param name="Id"></param>
        public void Delete(int Id)
        {
            using (Entities db = new Entities())
            {
                db.Specials.Remove(db.Specials.Find(Id));
                db.SaveChangesAsync().Wait();
            }
        }

        /// <summary>
        /// 清空专题下的内容
        /// </summary>
        /// <param name="SpecialID"></param>
        /// <param name="ModelId"></param>
        public void Clear(string SpecialID, string ModelId, string TableName)
        {
            using (Entities db = new Entities())
            {
                db.Database.ExecuteSqlCommand("update " + TableName + " SET SpecialID=0 WHERE SpecialID IN (Select Id from CMS_Special where Path like ''+(select Path from CMS_Special where Id={0})+'%')", SpecialID);
            }
        }


    }
}